package com.jiecao.news.jiecaonews.backgroung;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.jiecao.news.jiecaonews.util.ManagerUtil;
import com.jiecao.news.jiecaonews.util.constants.Constants;
public class UpdateInfoTask extends AsyncTask<String, String, Void> {
	
	private static final String TAG = "UpdateInfoTask";
	private String mlocalVer;
	private String mnewVer;
	private int mupdateType = -1;
	private Context mcontext;

	public UpdateInfoTask(
			Context context) {
		mlocalVer =  ManagerUtil.getVerName(context);
		mcontext = context;
	}

	@Override
	protected Void doInBackground(String... params) {
		

		try {
			String verInfo = getversionInfo(Constants.UPDATE_INFO_URL
					+ "oldVer=" + mlocalVer);
			if (null == verInfo) {
				return null;
			}
			JSONArray jsonArray = new JSONArray(verInfo);
			String stateCode;
			if (jsonArray.length() <= 0) {
				return null;
			}
			JSONObject obj = jsonArray.getJSONObject(0);
			stateCode = obj.getString("stateCode");
			if (null == stateCode || stateCode.equals("1")) {
				return null;
			}
			mnewVer = obj.getString("version");
			mupdateType = Integer.valueOf(obj.getString("isForce"));
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从后台获取版本信息
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	private String getversionInfo(String url) throws IOException {
		URL target = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) target.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-Type", "text/html");
		conn.setRequestProperty("Accept", "text/html");
		conn.setConnectTimeout(4000);//设置4秒超时
		conn.connect();
		int code = conn.getResponseCode();
		Log.i(TAG, "code:" + code);
		if(!((code >= 200) && (code < 300))){
			return null;
		}
		
		InputStream in =  conn.getInputStream() ;
		
		
		StringBuilder sb = new StringBuilder();
		try {
				// 取出回应字串
				if ( in != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader( in, "UTF-8"),
							8192);
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					reader.close();
				}
		} catch (Exception e) {
			Log.e(TAG, "getversionInfo error!" + e.getMessage());
			e.printStackTrace();
			return sb.toString();
		}
		return sb.toString();
	}

	@Override
	protected void onPostExecute(Void result) {
		// 从服务器取更新信息，取到后判断是否要弹出更新框：
		if (mnewVer == null || mnewVer.equals("") || mlocalVer == null
				|| mlocalVer.equals("")) {
			return;
		}
		if (mnewVer.equals(mlocalVer)||(mupdateType!=0&&mupdateType!=1)) {
			return;
		}
		AlertDialog dialog = new AlertDialog.Builder(mcontext).create();
		String info = "当前版本" + mlocalVer + " ,发现新版本：" + mnewVer;
//		 if(mupdateType==0) {
			// 弹出更新框
			info += ",是否更新？";
			dialog.setButton(DialogInterface.BUTTON_POSITIVE, "更新",
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Log.i(TAG, "dialog do uodate");
							Uri uri = Uri.parse(Constants.UPDATE_SERVER
									+ Constants.UPDATE_APKNAME);
							Intent intent = new Intent(Intent.ACTION_VIEW, uri);
							mcontext.startActivity(intent);
							dialog.dismiss();
							Log.i(TAG, "dialog do update end");
						}
					});
			dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "暂不更新",
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							Log.i(TAG, "not uodate");
						}
					});
			
			dialog.setMessage(info);
			dialog.setCancelable(false);
			dialog.show();
//		}
		
		super.onPostExecute(result);
	}
	

}
